package com.culture.bootdemo.common.init;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wen
 * @DateTime: 2024/3/6 15:01
 * @Description: 初始化数据
 **/
@Slf4j
@Component
public class LoadScheduledExecutor implements InitializingBean {

    //任务调度线程池
    private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("Load Senitive Word init thread-%d").build());

    private static final List<Integer> SENSITIVE_WORD_LIST = new ArrayList<>();


    @Override
    public void afterPropertiesSet() {
        try {
            log.info("LoadSensitiveWordService start >>>");
            /**
             * 周期性执行任务:ScheduledExecutorService
             */
            scheduledExecutorService.scheduleAtFixedRate(this::initData, 0, 30, TimeUnit.SECONDS);
            log.info("LoadSensitiveWordService end list-size:{} >>>", SENSITIVE_WORD_LIST);
        } catch (Exception e) {
            log.error("LoadSensitiveWordService error:", e);
        }
    }

    private void initData() {
        try {
            int index = 1;
            while (true) {
                if (index == 5) {
                    break;
                }
                List<Integer> wordList = Arrays.asList(index * 10, index * 20);
                if (CollectionUtils.isEmpty(wordList)) {
                    break;
                }
                if (index == 1) {
                    SENSITIVE_WORD_LIST.clear();
                }
                SENSITIVE_WORD_LIST.addAll(wordList);
                ++index;
            }
        } catch (Exception e) {
            log.info("LoadSensitiveWordService error:", e);
        }
    }

    public List<Integer> getSensitiveWordList() {
        return SENSITIVE_WORD_LIST;
    }

}
